import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_oldman_health/api/auth_service.dart';
import 'package:flutter_oldman_health/models/response_data_model.dart';
import 'package:flutter_oldman_health/utils/encrypt_util.dart';
import 'package:flutter_oldman_health/utils/utils.dart';
import 'package:flutter_oldman_health/widget/common_container.dart';

import '../login_page.dart';

class ResetPswPage extends StatefulWidget {
  @override
  _ResetPswPageState createState() {
    return _ResetPswPageState();
  }
}

class _ResetPswPageState extends State<ResetPswPage> {
  final TextEditingController _controllerPhone = TextEditingController();
  final TextEditingController _controllerPsw = TextEditingController();
  final TextEditingController _controllerPsw2 = TextEditingController();
  final TextEditingController _controllerCode = TextEditingController();

  String textCodeButton = "获取验证码";
  int countdownTime = 0;
  bool waitingCode = false;
  Timer _timer;

  @override
  void dispose() {
    super.dispose();
    if (_timer != null) {
      _timer.cancel();
    }
  }

  startCountdown() {
    countdownTime = 59;
    final call = (timer) {
      setState(() {
        if (countdownTime < 1) {
          _timer.cancel();
          waitingCode = false;
          textCodeButton = "获取验证码";
        } else {
          countdownTime -= 1;
          textCodeButton = "${countdownTime}s后重新获得";
        }
      });
    };
    _timer = Timer.periodic(Duration(seconds: 1), call);
  }

  @override
  Widget build(BuildContext context) {
    Color normalColor = Color(0xff41BAB0);
    Color activeColor = Color(0xFFdddddd);

    new Future.delayed(new Duration(seconds: 3), () {
      return 1;
    })
        .timeout(new Duration(seconds: 2))
        .then((value) => print)
        .catchError(print)
        .whenComplete(() => print);

    return Scaffold(
      resizeToAvoidBottomInset: true,
        body: Container(
            color: Colors.white,
            child: SingleChildScrollView(
                child: Column(
              // verticalDirection:VerticalDirection.down,
              // mainAxisAlignment: MainAxisAlignment.start,
              // crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                _getTitle(),
                CommonContainer(
                    Row(children: [
                      Text("手机号:  ", style: TextStyle(fontSize: 18)),
                      Expanded(
                          flex: 1,
                          child: TextField(
                              inputFormatters: [
                                LengthLimitingTextInputFormatter(11),
                                FilteringTextInputFormatter.digitsOnly
                              ],
                              keyboardType: TextInputType.number,
                              controller: _controllerPhone,
                              maxLines: 1,
                              autofocus: true,
                              style: TextStyle(
                                  fontSize: 18,
                                  color: Colors.black87,
                                  fontWeight: FontWeight.w300),
                              // obscureText: true,
                              decoration: getInputDecoration("请输入手机号")))
                    ]),
                    margin: EdgeInsets.fromLTRB(20, 20, 20, 20)),
                CommonContainer(
                    Row(children: [
                      Text("密码:  ", style: TextStyle(fontSize: 18)),
                      Expanded(
                          flex: 1,
                          child: TextField(
                              obscureText: true,
                              controller: _controllerPsw,
                              maxLines: 1,
                              inputFormatters: [
                                LengthLimitingTextInputFormatter(12)
                              ],
                              autofocus: true,
                              style: TextStyle(
                                  fontSize: 18,
                                  color: Colors.black87,
                                  fontWeight: FontWeight.w300),
                              // obscureText: true,
                              decoration: getInputDecoration("请输入新密码")))
                    ]),
                    margin: EdgeInsets.fromLTRB(20, 0, 20, 20)),
                CommonContainer(
                    Row(children: [
                      Text("密码:  ", style: TextStyle(fontSize: 18)),
                      Expanded(
                          flex: 1,
                          child: TextField(
                              obscureText: true,
                              controller: _controllerPsw2,
                              maxLines: 1,
                              inputFormatters: [
                                LengthLimitingTextInputFormatter(12)
                              ],
                              autofocus: true,
                              style: TextStyle(
                                  fontSize: 18,
                                  color: Colors.black87,
                                  fontWeight: FontWeight.w300),
                              // obscureText: true,
                              decoration: getInputDecoration("请再次输入密码")))
                    ]),
                    margin: EdgeInsets.fromLTRB(20, 0, 20, 20)),
                Row(
                  children: [
                    Expanded(
                        flex: 1,
                        child: CommonContainer(
                            TextField(
                                controller: _controllerCode,
                                maxLines: 1,
                                keyboardType: TextInputType.number,
                                autofocus: true,
                                inputFormatters: [
                                  LengthLimitingTextInputFormatter(4),  FilteringTextInputFormatter.digitsOnly
                                ],
                                style: TextStyle(
                                    fontSize: 18,
                                    color: Colors.black87,
                                    fontWeight: FontWeight.w300),
                                // obscureText: true,
                                decoration: getInputDecoration("请输入验证码")),
                            margin: EdgeInsets.fromLTRB(20, 0, 10, 0))),
                    CommonContainer(
                        GestureDetector(
                      behavior: HitTestBehavior.translucent,
                          onTap: () async {
                            print(textCodeButton);
                            if (_controllerPhone.text == null ||                                      !Utils.phoneStr(_controllerPhone.text)||
                                !Utils.phoneStr(_controllerPhone.text)||
                                _controllerPhone.text.length != 11) {
                              EasyLoading.showInfo("手机号码输入有误");
                              return;
                            }
                            if (textCodeButton.length != 5) {
                              return;
                            }

                            var response =
                                await AuthService.requestVerificationCode(
                                    _controllerPhone.text);
                            if (response != null &&
                                response.statusCode == 200) {
                              EasyLoading.showSuccess('获取验证码成功');

                              ResponseDataModel<String> value =
                                  ResponseDataModel<String>.fromJson(
                                      response.data);
                              if (value.success()) {
                                setState(() {
                                  waitingCode = true;
                                  textCodeButton = "59s后重新获得";
                                });
                                startCountdown();
                              } else {
                                EasyLoading.showInfo(value.msg);
                              }
                            }

                            // ResponseDataModel<String> value =
                            //     await UserDao.requestVerificationCode(
                            //         textEditPhone);
                          },
                          child: Text(textCodeButton,
                              style: TextStyle(
                                  fontSize: 18,
                                  color:
                                      waitingCode ? activeColor : normalColor)),
                        ),
                        margin: EdgeInsets.only(right: 20),
                        padding: EdgeInsets.fromLTRB(16, 20, 16, 20))
                  ],
                ),
                Container(
                    margin: EdgeInsets.fromLTRB(20, 40, 20, 0),
                    padding: EdgeInsets.all(16),
                    child: GestureDetector(
                      behavior: HitTestBehavior.translucent,
                        onTap: () async {
                          if (_controllerPhone.text == null ||
                              !Utils.phoneStr(_controllerPhone.text)||
                              _controllerPhone.text.length != 11) {
                            EasyLoading.showInfo("手机号码输入有误");
                            return;
                          }
                          if (_controllerPsw.text == null ||
                              _controllerPsw2.text == null) {
                            EasyLoading.showInfo("请填写密码");
                            return;
                          }
                          if (_controllerPsw.text.length < 6) {
                            EasyLoading.showInfo("密码至少6位");
                            return;
                          }
                          if (_controllerPsw.text != _controllerPsw2.text) {
                            EasyLoading.showInfo("两次密码不一致");
                            return;
                          }
                          if (_controllerCode.text == null ||
                              _controllerCode.text.length < 4) {
                            EasyLoading.showInfo("请填写验证码");
                            return;
                          }
                          String encryptPsw = EncryptUtil.encodeMd5(
                              _controllerPsw.text + '!%&qishiyun110');
                          // Register register = Register(
                          //     name: _controllerName.text,
                          //     pass: encryptPsw,
                          //     phone: textEditPhone,
                          //     code: _controllerCode.text);
                          //

                          var response = await AuthService.resetPsw(
                              _controllerPhone.text,
                              encryptPsw,
                              _controllerCode.text);
                          if (response != null && response.statusCode == 200) {
                            ResponseDataModel<String> value1 =
                                ResponseDataModel.fromJson(response.data);
                            if (value1.success()) {
                              Navigator.pop(context);
                              EasyLoading.showSuccess('重置密码成功');
                              Navigator.of(context).pushReplacement(
                                  MaterialPageRoute(
                                      builder: (context) => LoginPage()));
                              _timer.cancel();
                            } else {
                              EasyLoading.showInfo(value1.msg);
                            }
                          }
                        },
                        child: FractionallySizedBox(
                            widthFactor: 1,
                            child: Text("确认",
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 18,
                                    color: Colors.white)))),
                    decoration: BoxDecoration(
                        border: Border.all(color: Color(0xFFEEEEEE), width: 1),
                        color: Color(0xff41BAB0),
                        borderRadius: BorderRadius.all(Radius.circular(58))))
              ]
            ))));

    // return
  }

  InputDecoration getInputDecoration(String hintText) {
    return InputDecoration(
        fillColor: Colors.red,
        hintText: hintText,
        hintStyle: TextStyle(fontSize:18),
        //InputBorder.none  OutlineInputBorder()
        border: InputBorder.none);
  }

  Widget _getTitle([String title = "忘记密码"]) {
    return Container(
        color: Colors.white,
        padding: EdgeInsets.fromLTRB(16, 46, 16, 0),
        child: FractionallySizedBox(
          widthFactor: 1,
          child: Stack(
            alignment: Alignment.center,
            children: [
              Positioned(
                left: 2,
                top: 5,
                child: GestureDetector(
                      behavior: HitTestBehavior.translucent,
                  onTap: () {
                    Navigator.pop(context);
                  },
                  child: Container(
                          child: Icon(Icons.arrow_back_ios),
                          padding: EdgeInsets.fromLTRB(15, 0, 20, 10)),
                ),
              ),
              Text(title,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      fontSize: 22,
                      color: Colors.black87,
                      fontWeight: FontWeight.normal)),
            ],
          ),
        ));
  }
}
